package com.nineclock.approve.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nineclock.approve.dto.*;
import com.nineclock.approve.mapper.ApproveDefinitionMapper;
import com.nineclock.approve.pojo.ApproveDefinition;
import com.nineclock.approve.service.ActivitiService;
import com.nineclock.approve.service.ApproveDefinitionService;
import com.nineclock.common.enums.ResponseEnum;
import com.nineclock.common.exception.NcException;
import com.nineclock.common.threadlocal.CurrentUserHolder;
import com.nineclock.common.utils.BeanHelper;
import com.nineclock.common.utils.JsonUtils;
import com.nineclock.common.utils.UUIDUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 黑马程序员
 * @Company http://www.ithiema.com
 * @Version 1.0
 */
@Service
@Slf4j
public class ApproveDefinitionServiceImpl implements ApproveDefinitionService {

    @Autowired
    ApproveDefinitionMapper approveDefinitionMapper;



    @Override
    public List<ApproveGroupDefinitionDto> queryApproveGroupDefinition() {

        List<ApproveGroupDefinitionDto> approveGroupDefinitionDtoList = new ArrayList<>();

        LambdaQueryWrapper<ApproveDefinition> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ApproveDefinition::getCompanyId, CurrentUserHolder.get().getCompanyId());
        wrapper.eq(ApproveDefinition::getIsValid, 1);
        //获取当前企业下所有的审批定义列表
        List<ApproveDefinition> approveDefinitionList = approveDefinitionMapper.selectList(wrapper);
        if(CollectionUtil.isNotEmpty(approveDefinitionList)){
            // 按照 group_type 字段 进行分组
            Map<String, List<ApproveDefinition>>
                    map = approveDefinitionList.stream().collect(Collectors.groupingBy(ApproveDefinition::getGroupType));

            //将map集合转换为 返回值类型
            //map的key值进行遍历
            for (String key : map.keySet()) {
                //一个map集合对应  ApproveGroupDefinitionDto
                ApproveGroupDefinitionDto approveGroupDefinitionDto = new ApproveGroupDefinitionDto();
                approveGroupDefinitionDto.setGroupType(key);
                approveGroupDefinitionDto.setDefinitionList(map.get(key));
                //添加到集合对象中
                approveGroupDefinitionDtoList.add(approveGroupDefinitionDto);
            }
        }

        return approveGroupDefinitionDtoList;
    }

    @Autowired
    ActivitiService activitiService;

    /**
     * 保存或者修改审批定义
     * @param approveDefinitionSaveDto
     */
    @Override
    public void saveOrEditApproveDefinition(ApproveDefinitionSaveDto approveDefinitionSaveDto) {
        //健壮性判断
        if(approveDefinitionSaveDto == null || approveDefinitionSaveDto.getBaseData() == null){
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }
        //获取 基础信息
        ApproveDefinitionBaseDataDto baseData = approveDefinitionSaveDto.getBaseData();

        //判断是 新增，修改
        //如果是 null，说明是新增
        if(StrUtil.isEmpty(baseData.getId())){
            //复制 基础信息 到 审批流程定义对象中
            ApproveDefinition definition = BeanHelper.copyProperties(baseData, ApproveDefinition.class);
            //设置其他字段
            //设置允许那些人发起审批
            List<AllowUserObjDto> allowUserJson = baseData.getAllowUserJson();
            definition.setAllowUserJson(JsonUtils.toString(allowUserJson));

            //获取表单数据
            List<ApproveDefinitionTableDataDto> tableData = approveDefinitionSaveDto.getTableData();

            definition.setFormJson(JsonUtils.toString(tableData));


            //获取流程定义对象
            String flowData = approveDefinitionSaveDto.getFlowData();
            //把flowData转换为json数组
            JSONArray jsonArray = JSONUtil.parseArray(flowData);
            //给每一个jsonObject扩展一个字段
            expandParamWithNodeKey(jsonArray);
            //设置流程 json数据
            definition.setFlowJson(JsonUtils.toString(jsonArray));

            //转换表单数据为 columns数据
            List<ColumnObjDto> columns = expandFieldKey(approveDefinitionSaveDto);
            //设置表单列值
            definition.setColumns(JsonUtils.toString(columns));

            //设置唯一的表名
            definition.setTableName("flow_" + UUIDUtils.getUUID());

            definition.setCompanyId(CurrentUserHolder.get().getCompanyId() + "");
            definition.setDataFrom("1"); //来源 （自定义）

            definition.setIsValid("1");
            definition.setCreateTime(new Date());


            approveDefinitionMapper.insert(definition);

            //新增完成后，把 流程定义 部署到activiti中
            activitiService.deployProcessToActiviti(definition);

        }
        //否则是修改操作
        else {
            ApproveDefinition definition = approveDefinitionMapper.selectById(baseData.getId());

            definition.setGroupType(baseData.getGroupType());
            definition.setName(baseData.getName());
            //设置 那些人可以发起流程
            List<AllowUserObjDto> allowUserJson = baseData.getAllowUserJson();
            definition.setAllowUserJson(JsonUtils.toString(allowUserJson));

            definition.setDescription(baseData.getDescription());
            definition.setIcon(baseData.getIcon());
            definition.setOpinionPrompt(baseData.getOpinionPrompt());
            definition.setOpinionRequired(baseData.getOpinionRequired());
            definition.setSeq(baseData.getSeq());

            //获取表单数据
            List<ApproveDefinitionTableDataDto> tableData = approveDefinitionSaveDto.getTableData();

            definition.setFormJson(JsonUtils.toString(tableData));


            //获取流程定义对象
            String flowData = approveDefinitionSaveDto.getFlowData();
            //把flowData转换为json数组
            JSONArray jsonArray = JSONUtil.parseArray(flowData);
            //给每一个jsonObject扩展一个字段
            expandParamWithNodeKey(jsonArray);
            //设置流程 json数据
            definition.setFlowJson(JsonUtils.toString(jsonArray));

            //转换表单数据为 columns数据
            List<ColumnObjDto> columns = expandFieldKey(approveDefinitionSaveDto);
            //设置表单列值
            definition.setColumns(JsonUtils.toString(columns));


            //设置其他字段
            definition.setUpdateTime(new Date());
            //更新到数据库
            approveDefinitionMapper.updateById(definition);

            //更新完成后，把 流程定义 部署到activiti中
            //把部署到activiti中的流程定义 删除
            activitiService.dropProcessFromActiviti(definition);

            //把 流程定义 部署到activiti中
            activitiService.deployProcessToActiviti(definition);

        }

    }

    @Override
    public ApproveDefinitionResultDto queryById(String id) {
        if(id == null){
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }
        //根据id获取定义对象
        ApproveDefinition definition = approveDefinitionMapper.selectById(id);

        //封装基础信息
        //把 基础数据复制到 baseData中
        ApproveDefinitionBaseDataDto baseData
                = BeanHelper.copyProperties(definition, ApproveDefinitionBaseDataDto.class);
        //把 allowUserJson转换为 List集合，并存储到 baseData中
        String allowUserJson = definition.getAllowUserJson();
        List<AllowUserObjDto> allowUserObjList = JsonUtils.toList(allowUserJson, AllowUserObjDto.class);
        baseData.setAllowUserJson(allowUserObjList);

        //获取流程json
        String flowJson = definition.getFlowJson();

        //获取表单数据
        String formJson = definition.getFormJson();
        List<ApproveDefinitionTableDataResultDto> tableData = JsonUtils.toList(formJson, ApproveDefinitionTableDataResultDto.class);

        //创建返回值
        ApproveDefinitionResultDto resultDto = new ApproveDefinitionResultDto();

        resultDto
                .setBaseData(baseData)
                .setTableData(tableData)
                .setFlowData(flowJson);

        return resultDto;
    }

    /**
     * 扩充参数 : fieldKey
     * @param approveDefinitionDto
     * @return
     */
    private List<ColumnObjDto> expandFieldKey(ApproveDefinitionSaveDto approveDefinitionDto) {
        List<ColumnObjDto> columns = new ArrayList<>();

        for (ApproveDefinitionTableDataDto tableData : approveDefinitionDto.getTableData()) {
            if(StrUtil.isEmpty(tableData.getFieldKey())){
                tableData.setFieldKey(UUIDUtils.getUUID());
            }

            columns.add(new ColumnObjDto(tableData.getFieldKey(), tableData.getLab(), tableData.getTitle(), "1"));
        }
        return columns;
    }

    private void expandParamWithNodeKey(JSONArray jsonArray) {
        for(int i = 0; i < jsonArray.size(); i++){
            JSONObject jsonNode = (JSONObject) jsonArray.get(i);

            String nodeKey = jsonNode.getStr("nodeKey");
            if(StrUtil.isEmpty(nodeKey)){
                jsonNode.put("nodeKey", UUIDUtils.getUUID());
            }

            //处理网关节点的内部节点 nodeKey
            String type = jsonNode.getStr("type");
            if("condition".equals(type)){

                JSONArray batchArray = (JSONArray) jsonNode.get("node");
                if(batchArray!=null && batchArray.size()>0){

                    for (int j = 0; j < batchArray.size(); j++) {
                        JSONArray innerArray = (JSONArray) batchArray.get(j);

                        if(innerArray!=null && innerArray.size()>0){
                            for (int k = 0; k < innerArray.size(); k++) {
                                JSONObject node = (JSONObject) innerArray.get(k);
                                if(!node.containsKey("nodeKey")){
                                    node.put("nodeKey", UUIDUtils.getUUID());
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
